package pers.ljf.escloud.controller.app;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import pers.ljf.escloud.common.dto.FileItemDTO;
import pers.ljf.escloud.common.utils.HttpUtil;
import pers.ljf.escloud.dao.entity.app.ShortLinkConfig;
import pers.ljf.escloud.service.modules.app.FileService;
import pers.ljf.escloud.service.modules.app.ShortLinkConfigService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Controller
public class ShortLinkController {

    private static final String domain = "http://localhost:8080";

    @Resource
    private ShortLinkConfigService shortLinkConfigService;

    @Resource
    private FileService fileService;

    /**
     * 凭借/app/file/short-link所给的key找到对应的文件地址，然后内部重定向到/app/file/directLink
     *
     * @param key
     * @return
     */
    @GetMapping("/s/{key}")
    public String parseShortKey(@PathVariable String key, HttpServletResponse response) throws IOException {
        ShortLinkConfig shortLinkConfig = shortLinkConfigService.findByKey(key);
        if (shortLinkConfig == null) {
            throw new RuntimeException("此直链不存在或已失效.");
        }
//
//        //"/app/file/directLink/{fullPath}"
//        String url1 = shortLinkConfig.getUrl().replaceFirst("/","");
//        String url = URLUtil.encode(url1);
//        return "redirect:/app/file/directLink/" + url;
        FileItemDTO fileItem = fileService.getFileItem(shortLinkConfig.getUrl());

        String url = fileItem.getUrl();

        if (StrUtil.equalsIgnoreCase(FileUtil.extName(fileItem.getName()), "m3u8")) {
            String textContent = HttpUtil.getTextContent(url);
            response.setContentType("application/vnd.apple.mpegurl;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(textContent);
            out.flush();
            out.close();
            return null;
        }
        return "redirect:" + url;
    }
}
